package users

import (
	"context"
	"errors"
	"fmt"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/golang-jwt/jwt/v5"
	"star/internal/dao"
	"star/internal/model/entity"
	"star/utility"
)

func InfoAccount(ctx context.Context) (user *entity.Users, err error) {
	user = new(entity.Users)
	fmt.Println(g.RequestFromCtx(ctx))
	tokenString := g.RequestFromCtx(ctx).Request.Header.Get("Authorization")
	tokenClaims, _ := jwt.ParseWithClaims(tokenString, &UserClaims{}, func(t *jwt.Token) (interface{}, error) {
		return utility.JwtKey, nil
	})
	if claims, ok := tokenClaims.Claims.(*UserClaims); ok && tokenClaims.Valid {
		err = dao.Users.Ctx(ctx).Where("id", claims.ID).Scan(&user)
		if err != nil {
			return nil, errors.New("token解析失败")
		}
	}
	if user != nil {
		user.UpdatedAt = gtime.New()
	}
	return user, err
}

// 获取uid

func GetUid(ctx context.Context) (uint, error) {
	user, err := InfoAccount(ctx)
	if err != nil {
		return 0, err
	}
	return user.Id, nil
}
